package com.example.administrator.personalmail.Activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.cjj.MaterialRefreshLayout;
import com.cjj.MaterialRefreshListener;
import com.example.administrator.personalmail.R;
import com.example.administrator.personalmail.adapter.HotAdapter;
import com.example.administrator.personalmail.api.Contants;
import com.example.administrator.personalmail.model.Page;
import com.example.administrator.personalmail.model.Wares;
import com.example.administrator.personalmail.retrofitAPI.GetRequest_Interface;
import com.facebook.drawee.backends.pipeline.Fresco;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class WaresListActivity extends AppCompatActivity {
    private RecyclerView mRecyclerView;
    private MaterialRefreshLayout materialRefreshLayout;
    private TabLayout mTabLayout;
    private HotAdapter mHotAdapter;
    private Page<Wares> mPage;
    private ArrayList<Wares> mWares;
    private int totalPage=0;
    private int REFRESH=1;
    private int LOADMORE=2;
    private int state=0;
    final private int PAGE_SIZE = 10;
    private int curPage=1;
    private int orderBy=0;
    private long campaignId;
    private ImageView ivBack;

    public static final int TAG_DEFAULT=0;
    public static final int TAG_SALE=1;
    public static final int TAG_PRICE=2;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_warelist);
        campaignId = getIntent().getLongExtra("id",0);
        init();
        initTab();
//        Fresco.initialize(this);
        hotRerofit();
    }

    private void init() {
        mRecyclerView = findViewById(R.id.rv_detail);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));

        ivBack = findViewById(R.id.iv_back_detail);
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                WaresListActivity.this.finish();
            }
        });

        materialRefreshLayout = findViewById(R.id.mr_detail);
        materialRefreshLayout.setLoadMore(true);
        materialRefreshLayout.setMaterialRefreshListener(new MaterialRefreshListener() {
            @Override
            public void onRefresh(MaterialRefreshLayout materialRefreshLayout) {
                state=REFRESH;
                curPage=1;
                hotRerofit();
            }

            @Override
            public void onRefreshLoadMore(MaterialRefreshLayout materialRefreshLayout) {
                if (curPage<=totalPage){
                    state=LOADMORE;
                    curPage++;
                    hotRerofit();
                }else {
                    materialRefreshLayout.finishRefreshLoadMore();
                }
            }
        });
    }

    private void initTab(){
        mTabLayout = findViewById(R.id.tab_layout_detail);

        TabLayout.Tab tab= mTabLayout.newTab();
        tab.setText("默认");
        tab.setTag(TAG_DEFAULT);
        mTabLayout.addTab(tab);

        tab= mTabLayout.newTab();
        tab.setText("价格");
        tab.setTag(TAG_PRICE);
        mTabLayout.addTab(tab);

        tab= mTabLayout.newTab();
        tab.setText("销量");
        tab.setTag(TAG_SALE);
        mTabLayout.addTab(tab);


////MODE_FIXED标签栏不可滑动，各个标签会平分屏幕的宽度
//        tl.setTabMode(tabCount <= MOVABLE_COUNT ? TabLayout.MODE_FIXED : TabLayout.MODE_SCROLLABLE);
//        //指示条的颜色
//        tl.setSelectedTabIndicatorColor(getResources().getColor(android.R.color.holo_blue_dark));
//        tl.setSelectedTabIndicatorHeight((int) getResources().getDimension(R.dimen.indicatorHeight));
//        //关联tabLayout和ViewPager,两者的选择和滑动状态会相互影响
//        tl.setupWithViewPager(vp);
//        //自定义标签布局
//        for (int i = 0; i < tabs.size(); i++) {
//            TabLayout.Tab tab = tl.getTabAt(i);
//            TextView tv = (TextView) LayoutInflater.from(this).inflate(R.layout.tabview_main, tl, false);
//            tv.setText(tabs.get(i));
//            tab.setCustomView(tv);
//        }

        mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                orderBy = (int) tab.getTag();
                curPage = 1;
                state = 0;
                totalPage = 0;
                hotRerofit();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                orderBy = (int) tab.getTag();
                curPage = 1;
                state = 0;
                totalPage = 0;
                hotRerofit();
            }
        });
    }

    private void hotRerofit(){
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Contants.API.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        GetRequest_Interface service = retrofit.create(GetRequest_Interface.class);
        retrofit2.Call<Page<Wares>> call = service.waresListRequest(curPage,PAGE_SIZE,campaignId,orderBy);
        call.enqueue(new retrofit2.Callback<Page<Wares>>() {
            @Override
            public void onResponse(retrofit2.Call<Page<Wares>> call, retrofit2.Response<Page<Wares>> response) {
                mPage = response.body();
                if (state == LOADMORE) {
                    mHotAdapter.addData(mHotAdapter.getSize(),mPage.getList());
                    if (curPage==totalPage){
                        mHotAdapter.setFOOTER(true);
                    }
                    materialRefreshLayout.finishRefreshLoadMore();
                }else if (state == REFRESH){
                    mWares = mPage.getList();
                    mHotAdapter = new HotAdapter(mWares,WaresListActivity.this);
                    mHotAdapter.setOnItemClickListener(new HotAdapter.ItemClickListenner() {
                        @Override
                        public void onItemClick(int position) {
                            Intent intent = new Intent(WaresListActivity.this, WebDetailActivity.class);
                            intent.putExtra("wares",mWares.get(position));
                            startActivity(intent);
                        }
                    });
                    mHotAdapter.setFOOTER(false);
                    mRecyclerView.setAdapter(mHotAdapter);
                    materialRefreshLayout.finishRefresh();
                }else {
                    mWares = mPage.getList();
                    mHotAdapter = new HotAdapter(mWares,WaresListActivity.this);
                    mHotAdapter.setOnItemClickListener(new HotAdapter.ItemClickListenner() {
                        @Override
                        public void onItemClick(int position) {
                            Intent intent = new Intent(WaresListActivity.this, WebDetailActivity.class);
                            intent.putExtra("wares",mWares.get(position));
                            startActivity(intent);
                        }
                    });
                    mRecyclerView.setAdapter(mHotAdapter);

                    if (totalPage==0){
                        int page = mPage.getTotalCount()/10;
                        if (mPage.getTotalCount()%10 != 0){
                            totalPage = page+1;
                        }else {
                            totalPage = page;
                        }
                    }
                }

            }

            @Override
            public void onFailure(retrofit2.Call<Page<Wares>> call, Throwable t) {
                Log.e("---------","error");

            }
        });
    }

    @Override
    protected void onStop() {
        super.onStop();
    }
}
